package com.fable.cordova;

import com.BRMicro.Tools;
import com.rfid.uhf.UhfReader;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

/**
 * RFID读取插件
 *
 * @author afeey
 */
public class Rfid extends CordovaPlugin {

    private UhfReader reader;
    private String serialportPath = "/dev/ttyMT1";
    private int port = 12;

    @Override
    public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {

        if (action.equals("readEPC")) {

            Result result = readEPC();
            if (result.getSuccess()) {
                callbackContext.success(result.getData().toString());
            } else {
                callbackContext.error("read error." + result.getMessage());
            }
            return true;
        }
        return false;

    }

    /**
     * 读取EPC
     */
    private Result readEPC() {
        Result result = new Result();
        try {
            reader = UhfReader.getInstance(serialportPath, port);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setCode("202");
            result.setMessage("获取UhfReader异常");

            return result;
        }

        List<String> epcList = reader.inventoryTag();
        String epc = "";
        if (epcList != null && !epcList.isEmpty()) {
            epc = epcList.get(0);
        }

        result.setSuccess(true);
        result.setCode("200");
        result.setMessage("读取完成");
        result.setData(epc);
        return result;
    }

    /**
     * 读取用户数据
     */
    private String readUserData() throws Exception {
        reader = UhfReader.getInstance(serialportPath, port);

        List<String> epcList = reader.inventoryTag();
        if (epcList == null || epcList.isEmpty()) {
            throw new Exception("未读取到EPC");
        } else {
            String epc = epcList.get(0);

            int membank = UhfReader.MEMBANK_USER; //存储区
            int address = 0;
            int length = 1;
            String password = "00000000";
            byte[] accessPassword = Tools.HexString2Bytes(password);

            byte[] data = reader.readData(membank, address, length, accessPassword);
            if (data != null && data.length > 1) {
                return Tools.Bytes2HexString(data, data.length);
            } else {
                if (data != null) {
                    throw new Exception("读数据失败");
                }
                throw new Exception("读数据失败，返回null");
            }
        }
    }
}
